package com.example.demo.controller;

import com.example.demo.myenums.RegisterEnum;
import com.example.demo.pojo.User;
import com.example.demo.service.IUserService;
import com.example.demo.utils.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    @ResponseBody
    public User login(String username, String password, HttpServletRequest request) {
        HttpSession session = request.getSession();
        //TODO 数据库查询
        User isExistUser = userService.findByUsernameAndPassword(username, password);
        //TODO 判断
        if (isExistUser == null) {
            session.setAttribute("error","您输入的信息有误");
            return null;
        }
        //TODO 保存用户信息到session
        System.out.println(isExistUser);
        session.setAttribute("error",null);
        session.setAttribute("user", isExistUser);
        //TODO 返回
        return isExistUser;
    }

    @PostMapping("/register")
    public String register(User user) {
//        TODO 校验用户名是否存在
        user.setState(RegisterEnum.STATE_NO.code);
//        TODO 设置状态码 使用RegisterEnum 枚举类
        String uuid = CodeUtils.getRandomUUID();

//        TODO 生成激活码
//        TODO 发送激活码
//        TODO 完善用户信息并save
        user.setCode(uuid);
        User saveUser = userService.save(user);
//        TODO 重定向回登录
        System.out.println(saveUser);
        return "redirect:/";
    }
}
